const express = require("express")
const router = express.Router()
const visitorDB = require("../../db/visitorOrder")
const jwt = require("jsonwebtoken")
const adminDB = require("../../db/admin")
const nodemailer = require("nodemailer")
const { dateFromatStamp } = require("../../utils/dayjs")

// 密钥
const cort = "coderxinxin2022-04-15"

// 当前用户ID
let userInfoID = ""

// 用户预约
router.post("/visitor", async (req, res) => {
  try {
    const { name, phone, email, startTime, endTime } = req.body

    await visitorDB.create({ name, phone, email, startTime, endTime })

    // 将用户预约消息发送到每一位管理员账号中
    const adminList = await adminDB.find()
    adminList.forEach(async (item) => {
      await adminDB.findByIdAndUpdate(item._id, {
        $inc: { appointmentUnread: 1 },
        $push: {
          messageList: {
            title: "一条用户预约消息",
            des: `用户${name}提交了${dateFromatStamp(
              startTime,
              "YYYY-MM-DD"
            )}至${dateFromatStamp(
              endTime,
              "YYYY-MM-DD"
            )}的活动预约，请尽快处理！`,
            constType: 2,
          },
        },
      })
    })

    res.send({
      coed: 0,
      mes: "已收到您的预约，您的预约结果会通过邮箱通知您",
    })
  } catch (error) {
    res.send({
      code: 5,
      mse: "服务器异常，请稍后再试",
    })
  }
})

// 获取预约者信息列表
router.get("/gain", async (req, res) => {
  try {
    const { limit, skip } = req.query
    const subscribeList = await visitorDB
      .find(
        {},
        {},
        {
          sort: {
            time: -1,
          },
          limit: limit * 1,
          skip: skip * 1,
        }
      )
      .populate("handler", {
        name: 1,
        avatar: 1,
      })

    const allNums = await (await visitorDB.find()).length

    res.send({
      code: 0,
      mes: "预约者信息列表",
      data: {
        subscribeList,
        allNums,
      },
    })
  } catch (error) {
    console.log(error)
    res.send({
      code: 5,
      mes: "服务器异常,请稍后再试",
    })
  }
})

// 搜索获取预约者信息列表
router.get("/search", async (req, res) => {
  try {
    const { name, phone, email, startTime, endTime, resule, limit, skip } =
      req.query
    // console.log(startTime, typeof startTime)
    let subscribeList = []
    let allNums = 0

    // 查询全部
    if (resule == 3) {
      console.log("全部")
      subscribeList = await visitorDB
        .find(
          {},
          {},
          {
            sort: {
              time: -1,
            },
            limit: limit * 1,
            skip: skip * 1,
          }
        )
        .populate("handler", {
          name: 1,
          avatar: 1,
        })
      allNums = await (await visitorDB.find()).length
      // 含有名字 只有名字
      if (name) {
        subscribeList = await visitorDB.find().populate("handler", {
          name: 1,
          avatar: 1,
        })
        subscribeList = subscribeList.filter((item) => item.name.includes(name))
        // 含有电话
        subscribeList = subscribeList.filter((item) =>
          item.phone.includes(phone)
        )
        // 含有邮箱
        subscribeList = subscribeList.filter((item) =>
          item.email.includes(email)
        )
        // 含有时间
        if (startTime != 0) {
          subscribeList = subscribeList.filter((item) => {
            if (item.startTime >= startTime && item.endTime <= endTime) {
              return item
            }
          })
        }
        skip == 0
          ? (subscribeList = subscribeList.slice(skip * 1, limit * 1))
          : (subscribeList = subscribeList.slice(
              skip * 1,
              skip * 1 + limit * 1
            ))
        allNums = subscribeList.length
      }
      // 只有手机号
      else if (phone) {
        subscribeList = await visitorDB.find().populate("handler", {
          name: 1,
          avatar: 1,
        })
        subscribeList = subscribeList.filter((item) =>
          item.phone.includes(phone)
        )
        // 含有邮箱
        subscribeList = subscribeList.filter((item) =>
          item.email.includes(email)
        )
        // 含有时间
        if (startTime != 0) {
          subscribeList = subscribeList.filter((item) => {
            if (item.startTime >= startTime && item.endTime <= endTime) {
              return item
            }
          })
        }
        skip == 0
          ? (subscribeList = subscribeList.slice(skip * 1, limit * 1))
          : (subscribeList = subscribeList.slice(
              skip * 1,
              skip * 1 + limit * 1
            ))
        allNums = subscribeList.length
      }
      // 只有邮箱
      else if (email) {
        subscribeList = await visitorDB.find().populate("handler", {
          name: 1,
          avatar: 1,
        })
        subscribeList = subscribeList.filter((item) =>
          item.email.includes(email)
        )

        // 含有时间
        if (startTime != 0) {
          subscribeList = subscribeList.filter((item) => {
            if (item.startTime >= startTime && item.endTime <= endTime) {
              return item
            }
          })
        }
        skip == 0
          ? (subscribeList = subscribeList.slice(skip * 1, limit * 1))
          : (subscribeList = subscribeList.slice(
              skip * 1,
              skip * 1 + limit * 1
            ))
        allNums = subscribeList.length
      }
      // 只有时间
      else if (startTime != 0) {
        subscribeList = await visitorDB
          .find(
            {
              startTime: {
                $gte: startTime * 1,
              },
              endTime: {
                $lte: endTime * 1,
              },
            },
            {},
            {
              skip: skip * 1,
              limit: limit * 1,
            }
          )
          .populate("handler", {
            name: 1,
            avatar: 1,
          })
        allNums = await (
          await visitorDB.find({
            startTime: {
              $gte: startTime * 1,
            },
            endTime: {
              $lte: endTime * 1,
            },
          })
        ).length
      }
    } else {
      subscribeList = await visitorDB
        .find(
          { resule: resule * 1 },
          {},
          {
            sort: {
              time: -1,
            },
            limit: limit * 1,
            skip: skip * 1,
          }
        )
        .populate("handler", {
          name: 1,
          avatar: 1,
        })
      allNums = await (await visitorDB.find({ resule: resule * 1 })).length
      // 含有名字 只有名字
      if (name) {
        subscribeList = subscribeList.filter((item) => item.name.includes(name))
        // 含有电话
        subscribeList = subscribeList.filter((item) =>
          item.phone.includes(phone)
        )
        // 含有邮箱
        subscribeList = subscribeList.filter((item) =>
          item.email.includes(email)
        )
        // 含有时间
        if (startTime != 0) {
          subscribeList = subscribeList.filter((item) => {
            if (item.startTime >= startTime && item.endTime <= endTime) {
              return item
            }
          })
        }
        skip == 0
          ? (subscribeList = subscribeList.slice(skip * 1, limit * 1))
          : (subscribeList = subscribeList.slice(
              skip * 1,
              skip * 1 + limit * 1
            ))
        allNums = subscribeList.length
      }
      // 只有手机号
      else if (phone) {
        subscribeList = subscribeList.filter((item) =>
          item.phone.includes(phone)
        )
        // 含有邮箱
        subscribeList = subscribeList.filter((item) =>
          item.email.includes(email)
        )
        // 含有时间
        if (startTime != 0) {
          subscribeList = subscribeList.filter((item) => {
            if (item.startTime >= startTime && item.endTime <= endTime) {
              return item
            }
          })
        }
        skip == 0
          ? (subscribeList = subscribeList.slice(skip * 1, limit * 1))
          : (subscribeList = subscribeList.slice(
              skip * 1,
              skip * 1 + limit * 1
            ))
        allNums = subscribeList.length
      }
      // 只有邮箱
      else if (email) {
        subscribeList = subscribeList.filter((item) =>
          item.email.includes(email)
        )

        // 含有时间
        if (startTime != 0) {
          subscribeList = subscribeList.filter((item) => {
            if (item.startTime >= startTime && item.endTime <= endTime) {
              return item
            }
          })
        }
        skip == 0
          ? (subscribeList = subscribeList.slice(skip * 1, limit * 1))
          : (subscribeList = subscribeList.slice(
              skip * 1,
              skip * 1 + limit * 1
            ))
        allNums = subscribeList.length
      }
      // 只有时间
      else if (startTime != 0) {
        subscribeList = await visitorDB
          .find(
            {
              resule: resule * 1,
              startTime: {
                $gte: startTime * 1,
              },
              endTime: {
                $lte: endTime * 1,
              },
            },
            {},
            {
              skip: skip * 1,
              limit: limit * 1,
            }
          )
          .populate("handler", {
            name: 1,
            avatar: 1,
          })
        allNums = await (
          await visitorDB.find({
            resule: resule * 1,
            startTime: {
              $gte: startTime * 1,
            },
            endTime: {
              $lte: endTime * 1,
            },
          })
        ).length
      }
    }
    res.send({
      code: 0,
      mes: "搜索预约记录列表",
      data: {
        subscribeList,
        allNums,
      },
    })
  } catch (error) {
    console.log(error)
    res.send({
      code: 5,
      mes: "服务器异常，请稍后再试",
    })
  }
})

// 身份校验 检验是否为管理员
router.use(async (req, res, next) => {
  try {
    // 校验token
    // 获取请求头里面的token
    let token = (req.headers.authorization || "").slice(7)
    let info = null
    // 捕获错误
    try {
      info = jwt.verify(token, cort)
      const doc = await adminDB.findById(info._id)
      // 检测超管身份
      if (!doc.admintor)
        return res.send({
          code: 4,
          mes: "您不具有该权限",
        })
      if (!doc)
        return res.send({
          code: 4,
          mes: "系统检测到该账号已被注销",
        })
      // 检测密码是否更新
      if (info.pass !== doc.pass)
        return res.send({
          code: 4,
          mes: "密码已更新,请重新登录",
        })
      userInfoID = doc._id
      next()
    } catch (error) {
      return res.send({
        code: 4,
        mes: "登录信息已过期,请重新登录",
      })
    }
  } catch (error) {
    res.send({
      code: 5,
      mes: "服务器异常，请稍后再试",
    })
  }
})

// 处理预约进度
router.post("/handleSchedule", async (req, res) => {
  try {
    const { appointmentID, type } = req.body
    // 检测预约消息是否存在
    const doc = await visitorDB.findById(appointmentID)
    if (!doc)
      return res.send({
        code: 2,
        mes: "该预约消息已被删除",
      })
    // 查看进度是否被改变
    if (doc.resule !== 0)
      return res.send({
        code: 2,
        mes: "该预约消息状态已改变,无法进行修改",
      })
    // 修改
    await visitorDB.findByIdAndUpdate(appointmentID, {
      resule: type * 1,
      handler: userInfoID,
      handlerTime: Date.now(),
    })

    // 发送邮件 通知该用户
    // 发送邮件
    let transporter = nodemailer.createTransport({
      host: "smtp.qq.com",
      port: 587,
      secure: false,
      auth: {
        user: "coderhjx@foxmail.com",
        pass: "ctnmiovjbnsgdcgc",
      },
    })

    let opt = {}
    if (type == 1) {
      opt = {
        from: '"新新小朋友科技有限有限公司"<coderhjx@foxmail.com>',
        to: doc.email,
        subject: "【公益星】- 公益星活动预约通知", //主题
        html: `
        <h2>尊敬的${doc.name}，你好！</h2>
          您在公益星公益平台预约的活动申请已通过,后续我们将通过电话方式与您下一步详谈,请保持电话通畅
          `,
      }
    } else if (type == 2) {
      opt = {
        from: '"新新小朋友科技有限有限公司"<coderhjx@foxmail.com>',
        to: doc.email,
        subject: "【公益星】- 公益星活动预约通知", //主题
        html: `
        <h2>尊敬的${doc.name}，你好！</h2>
          很遗憾，由于最近平台活动申请人数已满，因此您在公益星公益平台预约的活动申请已被驳回，期待与您的下次合作,
          `,
      }
    }
    await transporter.sendMail(opt)

    await visitorDB.findByIdAndUpdate(appointmentID, {
      notify: true,
    })

    res.send({
      code: 0,
      mes: "处理成功, 已将结果用邮件方式通知",
    })
  } catch (error) {
    res.send({
      code: 5,
      mes: "服务器异常,请稍后再试",
    })
  }
})

// 删除预约记录
router.post("/delete", async (req, res) => {
  try {
    const { appointmentID } = req.body
    // 查询是否存在
    const doc = await visitorDB.findById(appointmentID)
    if (!doc)
      return res.send({
        code: 2,
        mes: "该预约记录不存在或已被删除，请刷新后重试",
      })
    await visitorDB.findByIdAndRemove(appointmentID)
    res.send({
      code: 0,
      mes: "删除成功",
    })
  } catch (error) {
    res.send({
      code: 5,
      mes: "服务器异常，请稍后再试",
    })
  }
})

module.exports = router
